express = require 'express'
ysHelper = require 'ys-helper'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
middlewares = require './middlewares'
swig = require 'swig'

app = express()

global.C = require './conf/config'
C.api = require './conf/apiConfig'
global.M = {
  common: require './libs'
  errors: ysHelper.errors
  Promise: require 'bluebird'
  _: require 'lodash'
}

if C.debug
  app.use '/static', express.static "#{__dirname}/static"

app.locals = {
  baseUrl: C.baseUrl
}

app.enable 'trust proxy'
app.use bodyParser.json()
app.use bodyParser.urlencoded {extended: false}
app.use cookieParser()

#session line

if C.debug
  swig.setDefaults {
    cache: false
  }
#add filter in swig
require('./filter') swig
app.set 'views', "#{__dirname}/views"
app.engine 'swig', swig.renderFile
app.set 'view engine', 'swig'

nsqWriter = new ysHelper.tools.nsqWriter C.nsqIp, C.nsqPort, C.debug
app.use ysHelper.expressMiddleWares.requestLogger nsqWriter, 'Web.Log', C.projectName, C.debug

#middleware before router
middlewares.before app

#routes
require('./router/routes') app

#middleware after router
middlewares.after app

app.use (req, res) ->
  if req.xhr
    res.status(404).json({status:false})
  else
    res.status(404).render '404'

opts = {}
ajax_opts = {}
app.use ysHelper.expressMiddleWares.errorNext opts, ajax_opts

s = app.listen C.port, ->
  host = s.address().address
  port = s.address().port
  console.log 'listen at http://%s:%s', host, port

module.exports = s